import { doError } from './apiError'

// 这里是规定后端返回的数据格式规范
export interface ResOptions<T> {
    data?: T
    code?: number
    msg?: string
}

const fetch = (url: string, options?: any): Promise<any> => {
    const config = useRuntimeConfig()
    // 获取配置域名
    let baseUrl = config.public.baseUrl
    // 拼接请求地址
    const reqUrl = baseUrl + url
    return new Promise((resolve, reject) => {
        useFetch(reqUrl, { ...options }).then(({ data, error }: any) => {
            const value: ResOptions<any> = data.value
            resolve(value)
            // 判断是否有错误产生
            if (error.value) {
                doError(error.value?.statusCode, reqUrl)
                reject(error.value)
            } else {
                resolve(ref(value).value)
            }
        }).catch((err: any) => {
            // 接口请求异常的操作写在这里
            console.log(err)
            reject(err)
        })
    })
}

export default new class Http {

    get(url: string, params?: any): Promise<any> {
        return fetch(url, { method: 'get', params })
    }

    post(url: string, params?: any): Promise<any> {
        return fetch(url, { method: 'post', params })
    }

    put(url: string, body?: any): Promise<any> {
        return fetch(url, { method: 'put', body })
    }

    delete(url: string, body?: any): Promise<any> {
        return fetch(url, { method: 'delete', body })
    }
}